<?php

declare(strict_types=1);

namespace App\Traits\Model\Admin;

use App\Scopes\Admin\Admin as AdminScope;
use Donjan\Casbin\Enforcer;

trait Admin
{
    /**
     * The "booting" method of the model.
     */
    protected function boot():void
    {
        parent::boot();
        static::addGlobalScope(new AdminScope);
    }

    /**
     * 局部查询
     * @param $query
     * @param $value
     */
    public function scopeStatus($query, $value, $alias='')
    {
        $query->where($this->getAlias($alias).'status', $value);
    }

    /**
     * 密码修改器
     * @param $value
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = password_hash($value, PASSWORD_BCRYPT);
    }

    /**
     * 添加角色
     * @param $roles
     * @return bool
     */
    public function addRole(array $roles)
    {
        if ($this->is_admin != 0) {
            return true;
        }
        foreach ($roles as $role) {
            Enforcer::addRoleForUserInDomain((string)$this->id, (string)$role, 'admin');
        }

        return true;
    }

    /**
     * 编辑角色
     * @param array $roles
     */
    public function updateRole(array $roles)
    {
        $roleEnforcers = Enforcer::getRolesForUser((string)$this->id, 'admin');

        foreach ($roleEnforcers as $roleEnforcer) { // 当前角色不在角色列表中则删除
            if (!in_array($roleEnforcer, $roles)) {
                Enforcer::deleteRoleForUserInDomain((string)$this->id, $roleEnforcer, 'admin');
            }
        }

        $this->addRole($roles);
    }
}
